package edu.nctu.csie.jichang.database.command;

import edu.nctu.csie.jichang.database.model.cell.DBDatabase;
import edu.nctu.csie.jichang.database.model.cell.DBRow;
import edu.nctu.csie.jichang.database.model.cell.DBSchema;
import edu.nctu.csie.jichang.database.model.cell.DBTable;

/**
 * 聯集
 * @author Jichang
 */
public class UnionCommand implements IDBCommand {

	private DBDatabase element1 = null;
	private DBDatabase element2 = null;

	public DBDatabase execute() {
		for(String tName : element1.getSchemaNames()){
			if(element2.hasSchema(tName)){
				unionSchema(element1.getSchema(tName),element2.getSchema(tName));
			}
		}
		return element1;
	}

	private void unionSchema(DBSchema pSchema1, DBSchema pSchema2) {
		for(String tTable:pSchema2.getTableNames()){
			if(pSchema1.hasTable(tTable)){
				unionTable(pSchema1.getTable(tTable),pSchema2.getTable(tTable));
			}else{
				pSchema1.addTable(tTable, pSchema2.getTable(tTable));
			}
		}
	}
	
	private void unionTable(DBTable pTable1, DBTable pTable2) {
		DBRow tRow = null;
		for(String tRowName:pTable2.getRowNames()){
			tRow = pTable2.getRow(tRowName);
			if(!pTable1.hasTheSameRow(tRow)){
				pTable1.addRow(tRow);
			}
		}
	}
	
	public void setOperand(DBDatabase pElement1, DBDatabase pElement2) {
		element1 = pElement1;
		element2 = pElement2;
	}
	public void setArgument(String pArg) {
	}

}
